<script setup lang='ts' name="user-management">
import type { VxeGridInstance, VxeGridListeners } from 'vxe-table'

import { useDicts } from '@/pages/company-org/hooks/use-dicts'
import { getSupplierList } from '@fl/api/fangjiaohui'
import { delCompanyOrg } from '@fl/api/iam-api'
import ButtonItem from '@fl/components/button-item.vue'
// import { useStoreDict } from '@fl/store/modules/dict'
import { ElButton, ElCard, ElCol, ElDatePicker, ElForm, ElFormItem, ElInput, ElRow, ElTag } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

import type { IRowV0 } from './types'

import AddUser from './component/add-user.vue'
import DetailItem from './component/detail.vue'
import { useTable } from './hooks/use-table'

// useStoreDict().init(['dict_htzlx', 'dict_yewulb'])

const { useDict } = useDicts()
const { addBtn, btns, gridOptions } = useTable()
const defaultTime = ref<[Date, Date]>([
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 2, 1, 23, 59, 59),
])

const state = {
    accountName: '', // 管理人
    // createName: '', // 创建人
    createTime: '',
    enterpriseName: '',
    legalRepresentative: '', // 企业法人

}
const form = ref({ ...state })

const router = useRouter()
const detail = ref<any>({})
const show = ref(true)
const detailItemRef = ref()
const addUserRef = ref()
const showAdd = ref(false)
const showId = ref('')
const xGrid = ref<VxeGridInstance<IRowV0>>()

const gridEvents: VxeGridListeners<IRowV0> = {
    pageChange({ currentPage, pageSize }) {
        if (gridOptions.pagerConfig) {
            gridOptions.pagerConfig.currentPage = currentPage
            gridOptions.pagerConfig.pageSize = pageSize
        }
        getData()
    },
}

async function getData(currentPage?: any, pageSize?: any) {
    if (currentPage && pageSize) {
        gridOptions.pagerConfig.currentPage = currentPage
        gridOptions.pagerConfig.pageSize = pageSize
    }

    gridOptions.loading = true
    getSupplierList({
        ...form.value,
        endTime: formatTime(form.value.createTime[1]),
        page: gridOptions.pagerConfig.currentPage,
        size: gridOptions.pagerConfig.pageSize,
        startTime: formatTime(form.value.createTime[0]),
    }).then((res: any) => {
        if (res.code === 200) {
            const data = res.rows ?? []
            gridOptions.loading = false
            gridOptions.pagerConfig.total = res.total
            gridOptions.data = data
        }
        else {
            ElMessage.error(res.msg)
        }
    }).finally(() => {
        gridOptions.loading = false
    })
}

function formatTime(time) {
    if (!time)
        return ''
    return `${new Date(time).toJSON().substring(0, 10)} ${new Date(time).toTimeString().substring(0, 8)}`
}

function reset() {
    form.value = { ...state }
    getData()
}

async function doAction(item: any, row: any) {
    switch (item.value) {
        case 'add':
            detail.value = cloneDeep(row)
            showAdd.value = true
            showId.value = String(row.id)
            break
        case 'edit':
            router.push(`/house-source-center/fair/user-management-edit?id=${row.id}`)
            break
        case 'view':
            showId.value = String(row.id)
            show.value = false
            break
        case 'delete':
            delCompanyOrg(String(row.id)).then((res) => {
                if (res.code === 200) {
                    ElMessage.success('保存成功')
                    setTimeout(() => {
                        getData(1, 10)
                    }, 500)
                }
            })
            getData()
            break
        default:
            break
    }
}

function doAdd() {
    router.push('/house-source-center/fair/user-management-add')
}

function toggleAllCheckboxEvent() {
    const $grid = xGrid.value
    if ($grid)
        $grid.toggleAllCheckboxRow()
}

function toggleCheckboxEvent(row) {
    const $grid = xGrid.value
    if ($grid)
        $grid.toggleCheckboxRow(row)
}

watch(show, (val: boolean) => {
    if (val)
        reset()
})

getData()
</script>

<template>
    <template v-if="show">
        <ElCard mb-20>
            <ElForm :inline="true"
                    :model="form"
                    label-width="100"
                    class="query_form"
            >
                <ElRow>
                    <ElCol :span="8">
                        <ElFormItem label="添加时间区间:">
                            <ElDatePicker v-model="form.createTime"
                                          :default-time="defaultTime"
                                          type="daterange"
                                          range-separator="-"
                                          format="YYYY/MM/DD"
                                          start-placeholder="开始日期"
                                          end-placeholder="结束日期"
                            />
                        </ElFormItem>
                    </ElCol>

                    <ElCol :span="8">
                        <ElFormItem label="企业名称:">
                            <ElInput v-model="form.enterpriseName"
                                     placeholder="请输入"
                                     clearable
                            />
                        </ElFormItem>
                    </ElCol>
                    <!--
                    <ElCol :span="8">
                        <ElFormItem label="添加人:">
                            <ElInput v-model="form.createName"
                                     placeholder="请输入"
                                     clearable
                            />
                        </ElFormItem>
                    </ElCol> -->

                    <ElCol :span="8">
                        <ElFormItem label="房交会管理员:">
                            <ElInput v-model="form.accountName"
                                     placeholder="请输入"
                                     clearable
                            />
                        </ElFormItem>
                    </ElCol>

                    <ElCol :span="4"
                           :offset="20"
                           style="text-align: right;"
                    >
                        <ElButton type="primary"
                                  @click="getData(1, 10)"
                        >
                            搜索
                        </ElButton>

                        <ElButton @click="reset">
                            重置
                        </ElButton>
                    </ElCol>
                </ElRow>
            </ElForm>
        </ElCard>

        <ElCard>
            <div class="mb-20">
                <ElButton type="primary"
                          @click="doAdd"
                >
                    + 添加企业
                </ElButton>
            </div>
            <!-- 列表 -->
            <vxe-grid ref="xGrid"
                      v-bind="gridOptions"
                      v-on="gridEvents"
            >
                <template #checkbox_header="{ checked, indeterminate }">
                    <span class="custom-checkbox"
                          @click.stop="toggleAllCheckboxEvent"
                    >
                        <i v-if="indeterminate"
                           class="vxe-icon-square-minus-fill"
                        />

                        <i v-else-if="checked"
                           class="vxe-icon-square-checked-fill"
                        />

                        <i v-else
                           class="vxe-icon-checkbox-unchecked"
                        />
                    </span>
                </template>

                <template #checkbox_cell="{ row, checked, indeterminate }">
                    <span class="custom-checkbox"
                          @click.stop="toggleCheckboxEvent(row)"
                    >
                        <i v-if="indeterminate"
                           class="vxe-icon-square-minus-fill"
                        />

                        <i v-else-if="checked"
                           class="vxe-icon-square-checked-fill"
                        />

                        <i v-else
                           class="vxe-icon-checkbox-unchecked"
                        />
                    </span>
                </template>

                <template #enterpriseLevelId="{ row }">
                    <div class="flex gap-2">
                        <ElTag :type=" row?.enterpriseLevelId === '1' ? 'warning' : 'success'">
                            {{ row.enterpriseLevel }}
                        </ElTag>
                    </div>
                </template>

                <template #status="{ row }">
                    {{ useDict('EnterpriseStatus', row.status) }}
                </template>

                <template #catTypeId="{ row }">
                    {{ row.catType }}
                </template>

                <template #operate="{ row }">
                    <ButtonItem :btns="(row?.steward === '0' && row?.enterpriseLevelId === '2') ? [...btns, addBtn] : btns "
                                @btn-click="doAction($event, row)"
                    />
                </template>
            </vxe-grid>
        </ElCard>
    </template>

    <DetailItem v-else
                key="detail"
                ref="detailItemRef"
                v-model="show"
                :show-id="showId"
                @confirm="getData"
    />

    <AddUser v-if="showAdd"
             key="add"
             ref="addUserRef"
             v-model="showAdd"
             :show-id="showId"
             :data="detail"
             @confirm="getData"
    />
</template>

<style lang="less" scoped>
.query_form {
    :deep(.el-form-item__content) {
        width: 250px;
    }
}
</style>
